<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :immediate-check="false"
  >
    <comment-item
      @replyHandler="$emit('replyHandler', $event)"
      v-for="item in list"
      :key="item.com_id"
      :comment="item"
    />
  </van-list>
</template>
<script>
import { getCommentListAPi } from "@/api/Article";
import CommentItem from "./comment-item.vue";
export default {
  name: "CommentList",
  components: { CommentItem },
  props: {
    // 文章ID  评论ID
    sourceId: {
      type: [String, Number],
      required: true,
    },
    list: {
      type: Array,
      required: true,
      default: () => [],
    },
    type: {
      type: String,
      default: "a",
    },
  },
  data() {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      pageSize: 10,
      offset: null,
    };
  },
  created() {
    this.loading = true;
    this.onLoad();
  },
  methods: {
    async onLoad() {
      try {
        // 1. 请求获取数据
        let { data } = await getCommentListAPi({
          type: this.type,
          source: this.sourceId,
          offset: this.offset,
          limit: this.pageSize,
        });
        // 2. 将数据追加给列表
        this.list.push(...data.data.results);
        // 3. 关闭loading
        this.loading = false;
        // 4. 判断是否结束
        if (data.data.results.length < this.pageSize) {
          this.finished = true;
        } else {
          this.offset = data.data.last_id;
        }
        // 将评论或回复总数量传递到外面去
        this.$emit("sendTotal", data.data.total_count);
      } catch (error) {
        // 5. 是否出错
        this.loading = false;
        console.log(error);
      }
    },
  },
};
</script>
